
let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS, ERROR } = require('../utils/result');//结果
let { HOST } = require('../utils/CONSTANT');//常量模块
let HS256 = require('../utils/hs256');
let uuid = require('uuid');//第三方的中间件，有v1(),v3()....v5()方法可以自动生成身份识别id


//注册
/*
    判断用户是否已经注册
    用户未注册，则注册
*/
function registerModel() {
    return async (req, res) => {
        //获取用户提交的数据
        let { username = '', password = '', code = '' } = req.body;
        //后台需要对接收到的数据进行表单校验
        if (username == '') {
            ERROR(res, '请输入正确的用户名', null);
            return;
        }
        //对验证码进行判断
        // console.log('注册页面收到验证码：', code);
        // console.log('服务端存储的验证码：', req.session.codeText);
        if (code.toLowerCase() != req.session.codeText.toLowerCase()) {
            ERROR(res, '验证码不正确', null);
            return;
        }
        // if (code != 'XXY4') {
        //     ERROR(res, '验证码不正确', null);
        //     return;
        // }

        if (await existUser(username)) {//用户已注册，或报错
            ERROR(res, '出错', '用户已注册');
            return;
        }
        let rst = await register(username, HS256(password));//注册   
        rst ? SUCCESS(res, null) : ERROR(res, '注册失败', rst);
    };
}

//判断用户是否已注册
async function existUser(username) {
    let [err, data] = await to(db.query(`SELECT * FROM member WHERE username=?`, [username]));
    return err || data.length > 0 ? true : false;//用户已注册，或者报错 true     未注册，false
}

//注册功能
function register(username, pwd) {
    return db.query(`INSERT INTO member (uid,username,password,head_photo_url,createdate) VALUES (?,?,?,?,?)`,
        [uuid.v1(), username, pwd, 'image_source/head_photo/girl_head_03.png', Date.now()]);
}


module.exports = registerModel;